package com.yunxin.core.admin.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.core.admin.command.UserSonAddCommand;
import com.yunxin.core.admin.command.UserSonPageCommand;
import com.yunxin.core.admin.domain.*;
import com.yunxin.core.admin.service.*;
import com.yunxin.core.admin.mapper.AdminUserSonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【sys_user_son(商户用户团队关系表)】的数据库操作Service实现
* @createDate 2024-07-24 17:03:56
*/
@DS("admin")
@Service
public class AdminUserSonServiceImpl extends ServiceImpl<AdminUserSonMapper, AdminUserSon>
    implements AdminUserSonService{

    @Autowired
    @Lazy
    private AdminUserService adminUserService;
    @Autowired
    @Lazy
    private AdminUserMerchantService adminUserMerchantService;
    @Autowired
    @Lazy
    private AdminUserRoleService adminUserRoleService;
    @Autowired
    @Lazy
    private AdminRoleService adminRoleService;
    @Autowired
    @Lazy
    private AdminUserTeamShipService adminUserTeamShipService;
    @Autowired
    @Lazy
    private AdminTeamService adminTeamService;

    @Override
    public Page<AdminUser> getUserPage(UserSonPageCommand command) {
        Page<AdminUser> page=new Page<>(command.getPageNum().longValue(),command.getPageSize().longValue());
        LambdaQueryWrapper<AdminUserSon> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUserSon::getUserId,command.getUserId());
        AdminUserSon adminUserSon = this.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(adminUserSon)){
            return page;
        }
        queryWrapper.clear();
        queryWrapper.select(AdminUserSon::getUserId)
                .eq(AdminUserSon::getOnlyNo,adminUserSon.getOnlyNo())
                .ne(AdminUserSon::getUserId,command.getUserId());
        List<Integer> userIds = this.list(queryWrapper).stream().map(i -> i.getUserId()).toList();
        if (ObjectUtils.isEmpty(userIds) || userIds.size()<1){
            return page;
        }
        LambdaQueryWrapper<AdminUser> adminUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
        adminUserLambdaQueryWrapper.in(AdminUser::getId,userIds)
                .eq(AdminUser::getStatus,1)
                .orderByDesc(AdminUser::getId);
        adminUserService.page(page,adminUserLambdaQueryWrapper);
        List<AdminUser> records = page.getRecords();

        if (!ObjectUtils.isEmpty(records)){
            //角色
            Map<Long,List<Long>> userRoleMap=new HashMap<>();
            Map<Long, AdminRole> roleMap = new HashMap<>();
            //查询角色
            Set<Integer> resultUserIds = records.stream().map(i -> i.getId()).collect(Collectors.toSet());
            LambdaQueryWrapper<AdminUserRole> userRoleLambdaQueryWrapper=new LambdaQueryWrapper<>();
            userRoleLambdaQueryWrapper.in(AdminUserRole::getUserId,resultUserIds);
            List<AdminUserRole> roleList = adminUserRoleService.list(userRoleLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(roleList)&&roleList.size()>0){
                List<Long> roleIds=new ArrayList<>();
                for (AdminUserRole adminUserRole : roleList) {
                    roleIds.add(adminUserRole.getRoleId());
                    List<Long> roleIdList = userRoleMap.getOrDefault(adminUserRole.getUserId(),new ArrayList<>());
                    roleIdList.add(adminUserRole.getRoleId());
                    userRoleMap.put(adminUserRole.getUserId(),roleIdList);
                }
                if (!roleIds.isEmpty()){
                    List<AdminRole> adminRoles = adminRoleService.listByIds(roleIds);
                    roleMap = adminRoles.stream().collect(Collectors.toMap(AdminRole::getId, obj -> obj));
                }
            }

            //团队
            Map<Integer,List<Integer>> userTeamMap=new HashMap<>();
            Map<Integer, AdminTeam> teamMap = new HashMap<>();
            //查询团队
            LambdaQueryWrapper<AdminUserTeamShip> teamShipLambdaQueryWrapper=new LambdaQueryWrapper<>();
            teamShipLambdaQueryWrapper.in(AdminUserTeamShip::getUserMerchantId,resultUserIds);
            List<AdminUserTeamShip> teamShipList = adminUserTeamShipService.list(teamShipLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(teamShipList)&&teamShipList.size()>0){
                List<Integer> teamIds=new ArrayList<>();
                for (AdminUserTeamShip adminUserTeamShip : teamShipList) {
                    teamIds.add(adminUserTeamShip.getTeamId());
                    List<Integer> teamIdList = userTeamMap.getOrDefault(adminUserTeamShip.getUserMerchantId(), new ArrayList<>());
                    teamIdList.add(adminUserTeamShip.getTeamId());
                    userTeamMap.put(adminUserTeamShip.getUserMerchantId(),teamIdList);
                }
                if (!teamIds.isEmpty()){
                    List<AdminTeam> adminTeams = adminTeamService.listByIds(teamIds);
                    teamMap = adminTeams.stream().collect(Collectors.toMap(AdminTeam::getId, obj -> obj));
                }
            }

            for (AdminUser record : records) {
                //组装角色
                List<Long> roleIds = userRoleMap.get(record.getId().longValue());
                List<AdminRole> roles=new ArrayList<>();
                if (!roleIds.isEmpty()){
                    for (Long roleId : roleIds) {
                        roles.add(roleMap.get(roleId));
                    }
                }
                record.setRoleList(roles);

                //组装团队
                List<Integer> teamIds = userTeamMap.get(record.getId());
                List<AdminTeam> teamList=new ArrayList<>();
                if (!teamIds.isEmpty()){
                    for (Integer teamId : teamIds) {
                        teamList.add(teamMap.get(teamId));
                    }
                }
                record.setTeamList(teamList);
            }
        }
        return page;
    }

    @Override
    public void addUseSon(UserSonAddCommand command) {
        LambdaQueryWrapper<AdminUserMerchant> userMerchantLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userMerchantLambdaQueryWrapper.eq(AdminUserMerchant::getUserId,command.getUserId());
        AdminUserMerchant userMerchant = adminUserMerchantService.getOne(userMerchantLambdaQueryWrapper);
        userMerchantLambdaQueryWrapper.clear();
        userMerchantLambdaQueryWrapper.eq(AdminUserMerchant::getUserId,command.getToUserId())
                .eq(AdminUserMerchant::getMerchantId,userMerchant.getMerchantId());
        long userMerchantCount = adminUserMerchantService.count(userMerchantLambdaQueryWrapper);
        if (userMerchantCount<1){
            throw new BusinessException("该用户不在同一商户下,拒绝绑定");
        }
        LambdaQueryWrapper<AdminUserSon> adminUserSonLambdaQueryWrapper=new LambdaQueryWrapper<>();
        adminUserSonLambdaQueryWrapper.in(AdminUserSon::getUserId,command.getUserId(),command.getToUserId());
        List<AdminUserSon> userSonList = this.list(adminUserSonLambdaQueryWrapper);
        List<AdminUserSon> adminUserSons=new ArrayList<>();
        if (ObjectUtils.isEmpty(userSonList)||userSonList.size()<1){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            LambdaQueryWrapper<AdminUserSon> userSonLambdaQueryWrapper=new LambdaQueryWrapper<>();
            userSonLambdaQueryWrapper.eq(AdminUserSon::getOnlyNo,uuid);
            long count = this.count(userSonLambdaQueryWrapper);
            while (count>0){
                uuid = UUID.randomUUID().toString().replace("-", "");
                userSonLambdaQueryWrapper.clear();
                userSonLambdaQueryWrapper.eq(AdminUserSon::getOnlyNo,uuid);
                count = this.count(userSonLambdaQueryWrapper);
            }
            AdminUserSon adminUserSon=new AdminUserSon();
            adminUserSon.setUserId(command.getUserId());
            adminUserSon.setOnlyNo(uuid);
            adminUserSon.setCreateTime(new Date());
            adminUserSons.add(adminUserSon);

            AdminUserSon adminToUserSon=new AdminUserSon();
            adminToUserSon.setUserId(command.getToUserId());
            adminToUserSon.setOnlyNo(uuid);
            adminToUserSon.setCreateTime(adminUserSon.getCreateTime());
            adminUserSons.add(adminToUserSon);
        }else if (userSonList.size()==1){
            AdminUserSon agoUserSon = userSonList.get(0);
            adminUserSons.add(agoUserSon);

            AdminUserSon adminUserSon=new AdminUserSon();
            if (agoUserSon.getUserId().intValue() == command.getToUserId()){
                adminUserSon.setUserId(command.getUserId());
            }else {
                adminUserSon.setUserId(command.getToUserId());
            }
            adminUserSon.setOnlyNo(agoUserSon.getOnlyNo());
            adminUserSon.setCreateTime(new Date());
            adminUserSons.add(adminUserSon);
        }else if (userSonList.size()==2){
            Map<Integer, AdminUserSon> adminUserSonMap = userSonList.stream().collect(Collectors.toMap(AdminUserSon::getUserId, obj -> obj));
            AdminUserSon adminUserSon = adminUserSonMap.get(command.getUserId());
            AdminUserSon adminToUserSon = adminUserSonMap.get(command.getToUserId());
            LambdaQueryWrapper<AdminUserSon> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AdminUserSon::getOnlyNo,adminToUserSon.getOnlyNo());
            List<AdminUserSon> adminToUserSonList = this.list(lambdaQueryWrapper);
            for (AdminUserSon userSon : adminToUserSonList) {
                userSon.setOnlyNo(adminUserSon.getOnlyNo());
                userSon.setUpdateTime(new Date());
            }
            adminUserSons.addAll(adminToUserSonList);
        }
        this.saveOrUpdateBatch(adminUserSons);
    }

    @Override
    public void deleteUseSonById(Integer userId,Integer id) {
        LambdaQueryWrapper<AdminUserSon> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUserSon::getUserId,id);
        AdminUserSon adminUserToSon = this.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(adminUserToSon)){
            throw new BusinessException("未找到资源");
        }
        LambdaQueryWrapper<AdminUserSon> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminUserSon::getOnlyNo,adminUserToSon.getOnlyNo())
                .eq(AdminUserSon::getUserId,userId);
        long count = this.count(lambdaQueryWrapper);
        if (count>0){
            this.remove(queryWrapper);
            return;
        }
        throw new BusinessException("该子账号不属于您,删除失败");
    }

    @Override
    public AdminUser cutUserByUserId(Integer userId, Integer id) {
        LambdaQueryWrapper<AdminUserSon> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminUserSon::getUserId,userId);
        AdminUserSon adminUserSon = this.getOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(adminUserSon)){
            throw new BusinessException("未找到资源,禁止切换");
        }
        lambdaQueryWrapper.clear();
        lambdaQueryWrapper.eq(AdminUserSon::getOnlyNo,adminUserSon.getOnlyNo())
                .eq(AdminUserSon::getUserId,id);
        long count = this.count(lambdaQueryWrapper);
        if (count<1){
            throw new BusinessException("未找到资源,禁止切换");
        }
        AdminUser adminUser = adminUserService.getById(id);
        if (adminUser.getStatus()==1){
            return adminUser;
        }else {
            throw new BusinessException("该账号已被封禁,禁止切换");
        }
    }


}




